package com.ws.framework.controller;

import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ws.framework.model.Code;
import com.ws.framework.model.Page;
import com.ws.framework.service.CodeService;
import com.ws.framework.service.AppService;

@Controller
@RequestMapping("code")
public class CodeController extends BaseController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	AppService registerService;
	@Autowired
	CodeService codeService;

	@RequestMapping("/index")
	public String index(HttpServletRequest request) {
		request.setAttribute("registers", registerService.selectAppByManager(this.getUserEntity().getUserName()));
		return "ftl/codeList";
	}

	@RequestMapping("/list")
	@ResponseBody
	public Object list(HttpServletRequest request, Page<Code> page, String appId, String codeName) {
		Map<String, Object> condition = Maps.newHashMap();
		if (!Strings.isNullOrEmpty(appId)) {
			condition.put("app_Id", appId);
			request.setAttribute("appId", appId);
		}
		if (!Strings.isNullOrEmpty(codeName)) {
			condition.put("code_name", codeName);
			request.setAttribute("code_name", codeName);
		}
		page.setCondition(condition);
		return codeService.select4Page(page);
	}

	@RequestMapping("/toAddInfo")
	public String toAddInfo(HttpServletRequest request) {
		request.setAttribute("registers", registerService.selectAppByManager(this.getUserEntity().getUserName()));
		return "ftl/codeForm";
	}
	@RequestMapping("/{id}/toEditInfo")
	public String toEditInfo(HttpServletRequest request, @PathVariable(required = true) Long id) {
		Code code = codeService.selectById(id);
		request.setAttribute("registers", Lists.newArrayList(registerService.selectAppById(code.getAppId())));
		request.setAttribute("record", code);
		request.setAttribute("readOnly", "readOnly");
		return "ftl/codeForm";
	}

	@RequestMapping("/addOrUpdateInfo")
	@ResponseBody
	public Object addOrUpdateInfo(HttpServletRequest request,Long id, Long appId, String codeName, String codeDesc) {
		try {
			if (Objects.isNull(appId) || Strings.isNullOrEmpty(codeName) || Strings.isNullOrEmpty(codeDesc))
				return fail(EnumSvrResult.ERROR_PARAMS);
			if (Objects.isNull(id))
				codeService.insertCode(new Code(appId, codeName, codeDesc));
			else {
				Code code = codeService.selectById(id);
				code.setCodeName(codeName);
				code.setCodeDesc(codeDesc);
				codeService.updateCode(code);
			}
			return success();
		} catch (DuplicateKeyException ex) {
			logger.error("新增或修改代码基本信息出错,唯一键重复, appId:{}, codeName:{}, codeDesc:{}", appId, codeName, codeDesc, ex);
			ResultJsonBean bean = fail(EnumSvrResult.ERROR_DUP_KEY);
			bean.setMessage("代码名称重复");
			return bean;
		} catch (Exception e) {
			logger.error("新增或修改代码基本信息出错, appId:{}, codeName:{}, codeDesc:{}", appId, codeName, codeDesc, e);
			return error();
		}
	}

	@RequestMapping(value = "/{id}/delete", method = RequestMethod.DELETE)
	@ResponseBody
	public Object delete(HttpServletRequest request, @PathVariable(required = true) Long id) {
		try {
			if (Objects.isNull(id))
				return fail(EnumSvrResult.ERROR_PARAMS);
			codeService.delete(id);
			return success();
		} catch (Exception e) {
			logger.error("删除代码出错, id:{}", id, e);
			return error();
		}
	}

	@RequestMapping("/{id}/toView")
	public String toView(HttpServletRequest request, @PathVariable(required = true) Long id) {
		Code code = codeService.selectById(id);
		request.setAttribute("context", Objects.isNull(code) ? "" : code.getCodeContext());
		return "ftl/codeView";
	}
	
	@RequestMapping("/{id}/toEdit")
	public String toEdit(HttpServletRequest request, @PathVariable(required = true) Long id) {
		Code code = codeService.selectById(id);
		request.setAttribute("context", Objects.isNull(code) ? "" : code.getCodeContext());
		request.setAttribute("id", id);
		return "ftl/codeEdit";
	}
	
	@RequestMapping(value = "/{id}/edit")
	@ResponseBody
	public Object edit(HttpServletRequest request, @PathVariable(required = true) Long id, @RequestBody String source) {
		try {
			codeService.updateContextById(source, id);
			return success();
		} catch (Exception e) {
			logger.error("根据id修改代码内容出错, id:{}, context:{}", id, source, e);
			return error();
		}
	}
	
	@RequestMapping(value = "/{id}/cacheClear", method = RequestMethod.GET)
	@ResponseBody
	public Object cacheClear(HttpServletRequest request, @PathVariable(required = true) Long id) {
		request.setAttribute("id", id);
		return success();
	}
}